/*
 * @Desc:
 * @Version: v1.00
 * @Author: went
 * @Date: 2023-06-02 10:01:38
 * @LastEditors: went
 * @LastEditTime: 2023-06-15 15:16:43
 */
/*
 * @Desc:
 * @Version: v1.00
 * @Author: went
 * @Date: 2023-05-29 11:01:03
 * @LastEditors: went
 * @LastEditTime: 2023-06-09 17:59:37
 */
/*
 * @Desc:
 * @Version: v1.00
 * @Author: went
 * @Date: 2021-08-26 10:16:51
 * @LastEditors: went
 * @LastEditTime: 2023-05-30 10:25:26
 */
import { createRouter, createWebHashHistory } from "vue-router";
import LocalCache from "@/utils/cache";
import { SYS_TOKEN } from "@/utils/global-constant";
import type { RouteRecordRaw } from "vue-router";
let prefix: any = "";
let indexRoute: any = {
  path: prefix + "/",
  name: "index",
  component: () => import("@/layout/BasicLayout.vue"),
  children: [], //-> 根据userMenus来决定 -> children
};
// 判断是 qiankun 环境则增加路由前缀
if ((window as any).__POWERED_BY_QIANKUN__) {
  // 由于在qiankun mount之前加载，获取不到props
  // 可在addRoutes中给静态路由配置前缀
  prefix = "/sub-app/JF-ISCTM1100-WEB";
} else {
  indexRoute.redirect = "/init";
}
const routes: RouteRecordRaw[] = [
  indexRoute,
  {
    path: prefix + "/login",
    name: "login",
    component: () => import("@/views/login/login.vue"),
    meta: {
      title: "自习吧",
    },
  },
  {
    path: prefix + "/init",
    name: "init",
    component: () => import("@/views/Init.vue"),
  },
  {
    path: prefix + "/:pathMatch(.*)*",
    name: "notFound",
    component: () => import("@/views/not-found/404.vue"),
  },
];

const router = createRouter({
  routes,
  history: createWebHashHistory(),
});

// 导航守卫
router.beforeEach((to, from, next) => {
  document.title = to.meta.title as string;
  const token = LocalCache.getSession(SYS_TOKEN);
  if ((window as any).__POWERED_BY_QIANKUN__) {
    //作为qiankun子应用运行
    if (to.path === prefix + "/init") {
      next();
    } else {
      if (to.path.includes(prefix)) {
        next();
      } else {
        next({ path: prefix + to.path });
      }
    }
  } else {
    //独立运行（门户鉴权）
    if (to.path === "/init") {
      next();
    } else {
      if (!token || token === "null") {
        //携带地址栏的token和orgCode跳转到init页面进行初始化
        let href = window.location.href;
        let w = href.slice(href.indexOf("?"));
        console.log(w);
        return { path: `/init${w}` };
      } else {
        next();
      }
    }
  }
});
export default router;
